package com.kob.backend.controller.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.ProductMapper;
import com.kob.backend.mapper.SellMapper;
import com.kob.backend.mapper.ShopMapper;
import com.kob.backend.pojo.product;
import com.kob.backend.pojo.sell;
import com.kob.backend.pojo.shop;
import com.kob.backend.service.product.ProductAddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ProductAddController {
    @Autowired
    private ProductAddService productAddService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SellMapper sellMapper;
    @Autowired
    private ProductMapper productMapper;
    @PostMapping("/product/add/")
    public Map<String,String> addproduct(@RequestParam Map<String,String>map)
    {

        String productname= map.get("productname");
        Double price= Double.parseDouble(map.get("price"));
        Integer inventory = Integer.parseInt(map.get("inventory"));
        String description = map.get("description");
        String photo = map.get("photo");
        String shopname=map.get("shopname");

        Map<String,String>map1=new HashMap<>();
        if(shopname==null||shopname.length()<=0)
        {
            map1.put("error_message","所属店铺名不能为空");
            return map1;
        }
        QueryWrapper queryWrapper=new QueryWrapper<shop>();
        queryWrapper.eq("shopname",shopname);
        shop this_shop= shopMapper.selectOne(queryWrapper);
        if(this_shop==null){
            map1.put("error_message","店铺不存在，请先注册店铺");
            return map1;
        }

        if(productname==null||productname.length()==0)
        {
            map1.put("error_message","商品名不能为空");
            return map1;
        }
        if(price==null)
        {
            map1.put("error_message","价格不能为空");
            return map1;
        }
        if(inventory==null)
        {
            map1.put("error_message","库存数不能为空");
            return map1;
        }

        product this_product = new product(null,productname,price,inventory,description,photo);
        productMapper.insert(this_product);
        Integer productid=this_product.getId();
        Integer shopid=shopMapper.getIdByname(shopname);
        sell this_sell=new sell(shopid,productid);
        sellMapper.insert(this_sell);
        map1.put("error_message","success");
        return map1;
    }
}
